<?php
namespace Com\Pay;

//威付通微信扫码支付

class WeiFuTongSMPay{

    private $config = array();

  
    public function __construct($send_data){
        $this->config = $send_data;
    }


    /*生成支付连接*/
    public function getUrl($order_info,$other = array()){
        /* 获取提交的订单交易金额 */
        $price = $order_info['paymoney'];
        //支付成功后跳转地址
        $returnUrl = $order_info['return_url'];
        /* 获取提交的后台回调地址 */
        $notifyUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/Api/NotifyCallback/WeifutongpayNotify';


        $Sumprice = $price * 100;
        $order_sn = $order_info['ordernumber'];
        $post_data = array(
            'service' =>   'pay.weixin.native',
            'version'    =>     '2.0',
            "mch_id"  => $this->config['mch_id'],
            "out_trade_no"  =>  $order_sn,
            'body' => 'CenterPay',
            'total_fee' => $Sumprice,
            'mch_create_ip' => getRealIp(),
            'notify_url'    => $notifyUrl,
//            'callback_url'    => $returnUrl,
            'nonce_str'    => mt_rand(11111111111,999999999999),
        );
        $ContentSign = $this->setParam($post_data,$this->config['mch_key'],false); // 计算出Sign
        $post_data['sign'] = $ContentSign; // Sign签名
        $tar_url = 'https://pay.swiftpass.cn/pay/gateway';
        $xml = $this->arrayToXml($post_data);
        $res = $this->https_request($tar_url,$xml);
        $res_arr = $this->xmlToArray($res);
        if(isset($res_arr)){
            return $res_arr;
        }
        return false;
    }

    private function setParam($param,$key,$IS_Notify){
        $str = "";
        ksort($param);
        foreach($param as $key1=>$val)  {
            if($IS_Notify && $key1 == 'sign') continue;
            $str.=$key1."=".$val."&";
        }
        $str = rtrim($str,'&');
        $sign = strtoupper(md5($str . '&key=' . $key));
        return $sign;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
//        file_put_contents('./sm.txt',var_export($data,true));
        $a  = file_get_contents('php://input');
        $data = $this->xmlToArray($a);
        $MySign = $this->setParam($data,$this->config['mch_key'],true);
        if($data['sign'] == $MySign){
            if($data['pay_result'] == '0' && $data['status'] == '0'){
                return true;
            }else{
                // 失败
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }


    private function https_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        //参数不为空则为post请求

        if (!empty($data)){

            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }


    // 去掉所有数组空格
    private function norim($xmlArr){
        $newarr = array();
        foreach ($xmlArr as $key => $value) {
            $key1 = trim($key);
            $value1 = trim($value);
            $newarr[$key1] = $value1;
        }
        return $newarr;
    }

    //将XML转为array
    private function xmlToArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }


    //数组转XML
    private function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

}
